<script setup>
import CustomButton from '@/components/CustomButton.vue'
import InputField from '@/components/InputField.vue'
import {
	ref,
	reactive
} from 'vue'

const padding = ref('0')
const pic = ref()
const imgSize = reactive({
	x: 0,
	y: 0
})
const preview = ref()
const colors = ['#e0e0e0', '#000000', '#ffffff', '#ff0000', '#00ff00', '#0000ff', '#b0cbe8', '#f6a241']
const color = ref('#f0f0f0')
const size = reactive({
	w: 240,
	h: 160
})

// 选择图片
const onPicker = () => {
	uni.chooseImage({
		count: 1,
		success: (res) => {
			res.tempFilePaths.forEach((item) => {
				console.log("item", item)
				pic.value = item

				uni.getImageInfo({
					src: pic.value,
					success: (rs => {
						console.log("rs", rs)
						imgSize.x = rs.width
						imgSize.y = rs.height
					})
				});
			})
		}
	})
}



// 生成并保存图片
const onSave = async () => {
	if (!pic.value) {
		uni.showToast({
			title: '请先选择图片',
			icon: 'none'
		})
		return
	}

	// 创建 Canvas 上下文
	const ctx = uni.createCanvasContext('myCanvas')
	try {
		// console.log("imageInfo", imageInfo)
		const innerPadding = Number(padding.value);
		const canvasWidth = imgSize.x + innerPadding * 2;
		const canvasHeight = imgSize.y + innerPadding * 2;

		size.w = canvasWidth
		size.h = canvasHeight

		// 1. 绘制背景颜色
		ctx.setFillStyle(color.value)
		ctx.fillRect(0, 0, canvasWidth, canvasHeight)

		// 2. 遍历绘制所有图片（居中显示，宽度占 Canvas 90%）
		await new Promise((resolve) => {
			ctx.drawImage(
				pic.value,
				innerPadding, // x 起始位置（居中）
				innerPadding, // y 位置
				imgSize.x, // 图片宽度
				imgSize.y // 图片高度（平分垂直空间）
			)
			setTimeout(resolve, 300);
		})

		// 执行绘制
		ctx.draw(false, async () => {
			// 3. 将 Canvas 保存为临时文件
			uni.canvasToTempFilePath({
				canvasId: 'myCanvas',
				success: (res) => {
					console.log("res.....", res)
					setTimeout(() => {
						preview.value = res.tempFilePath
					}, 90);
					// 4. 保存到系统相册
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: () => {
							uni.showToast({
								title: '保存成功'
							})
						},
						fail: (err) => {
							console.error('保存失败:', err)
							uni.showToast({
								title: '保存失败，请检查权限',
								icon: 'none'
							})
						}
					})
				},
				fail: (err) => {
					console.error('Canvas导出失败:', err)
					uni.showToast({
						title: '生成图片失败',
						icon: 'none'
					})
				}
			})
		})
	} catch (err) {
		console.error('绘制错误:', err)
		uni.showToast({
			title: '生成图片失败',
			icon: 'none'
		})
	}
}
</script>

<template>
	<view class="container">
		<CustomButton text="选择图片" @click="onPicker" backgroundColor="#409eff" />

		<view class="colors">
			<CustomButton class="color" text="" v-for="i in colors" :key="i" :backgroundColor="i" @click="color = i" />
		</view>

		<view class="imgs" :style="`background-color: ${color}`">
			<image :src="pic" class="img" mode="widthFix" />
		</view>

		<view>
			<text>size: </text>
			<text>{{ imgSize.x }} x {{ imgSize.y }}</text>
		</view>
		<InputField v-model="padding" label="边距" placeholder="请输入边距" />
		<CustomButton text="生成图片" @click="onSave" backgroundColor="#409eff" />

		<!-- 隐藏的图片 -->
		<image :src="preview" v-if="preview" class="draws" mode="widthFix" />

		<!-- 隐藏的 Canvas -->
		<canvas canvas-id="myCanvas" :style="{
			width: size.w + 'px',
			height: size.h + 'px',
			position: 'fixed',
			top: '0',
			left: '-9999px',
		}" />
	</view>
</template>

<style lang="scss" scoped>
.draws {
	width: 100%;
	margin-top: 20rpx;
}

.container {
	padding: 20rpx;
}

.colors {
	display: flex;
	flex-direction: row;
	flex-wrap: nowrap;
	gap: 10rpx;
	justify-content: space-around;
	margin: 20rpx 0;

	.color {
		flex: 1;
	}

}

.imgs {
	margin: 20rpx 0;
	border-radius: 16rpx;
	overflow: hidden;
}

.img {
	width: 100%;
	display: block;
}
</style>